<?php

namespace App\Jobs;

use App\Models\FormIds;
use App\Models\TemplatesLog;
use App\Models\Tmplmsgs;
use App\Models\TmplmsgsLog;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class MessageJobs implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    protected $templateInfo;//模板消息

    public function __construct($templateInfo)
    {
        $this->templateInfo = $templateInfo;
    }

    public function handle()
    {
        //查询TemplatesLog记录中是否有当天未推送的记录
        $lists = TemplatesLog::where('status',0)
            ->where('template_id',$this->templateInfo['template_id'])
            ->where('created_at',Carbon::now()->toDateString())
            ->get()->toArray();
        if(count($lists)){
            $lists = array_chunk($lists,500);
            foreach ($lists as $key=>$item){
                //0代表不需要更新到TemplatesLog
                dispatch((new MessageForJobs($item,$this->templateInfo,0))->onQueue('daduizhang_message_for'));
            }
        }else{
            //查询当前可推送的所有用户的openid
            $lists = FormIds::select('openid')->distinct('openid')->get()->toArray();
            //生成推送队列
            if($lists){
                //直接更新可欲推总数
                TmplmsgsLog::where('template_id',$this->templateInfo['template_id'])
                    ->whereDate('created_at',Carbon::now()->toDateString())
                    ->update(['total'=>count($lists)]);
                //分组生成队列
                $lists = array_chunk($lists,500);
                foreach ($lists as $key=>$item){
                    //1代表需要更新到TemplatesLog
                    dispatch((new MessageForJobs($item,$this->templateInfo,1))->onQueue('daduizhang_message_for'));
                }
            }
        }
    }

    public function failed(\Exception $e)
    {
        Log::error($e->getMessage());
    }



}
